package com.lw.edu.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lw.edu.entity.Subject;
import com.lw.edu.entity.excel.SubjectData;
import com.lw.edu.entity.subject.OneSubject;
import com.lw.edu.entity.subject.TwoSubject;
import com.lw.edu.listener.SubjectExcelListener;
import com.lw.edu.mapper.SubjectMapper;
import com.lw.edu.service.SubjectService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Service
public class SubjectServiceImpl extends ServiceImpl<SubjectMapper, Subject> implements SubjectService {
    //添加subject （课程分类）
    @Override
    public void addSubject(MultipartFile file) {
        try {
            EasyExcel.read( file.getInputStream(), SubjectData.class,new SubjectExcelListener(this) ).sheet().doRead();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //查询课程分类列表
    @Override
    public List<OneSubject> getAllSubject() {
        //1.查询所有一级分类
        List<Subject> oneSubjectList = baseMapper.selectList( new QueryWrapper<Subject>().eq( "parent_id", "0" ) );
        //2.在查询所有二级分类
        List<Subject> twoSubjectList = baseMapper.selectList( new QueryWrapper<Subject>().ne( "parent_id", "0" ) );
        //创建list集合，用于存储最终封装数据
        List<OneSubject> list=new ArrayList<>();
        //封装一级数据
        oneSubjectList.stream().forEach( item->{
            OneSubject oneSubject = new OneSubject();
            BeanUtils.copyProperties( item,oneSubject );
            list.add( oneSubject );
            //封装二级数据
            List<TwoSubject> children =new ArrayList<>();
            twoSubjectList.stream().forEach( child->{
                //判断当前二级分类是否属于当前的一级分类
                if (item.getId().equals(child.getParentId())){
                    TwoSubject twoSubject = new TwoSubject();
                    BeanUtils.copyProperties( child,twoSubject );
                    children.add( twoSubject );
                }
            } );
            //将二级数据放入一级数据中
            oneSubject.setChildren( children );
        } );
        return list;
    }
}
